<template>
  <div style="margin-top: 50px">
    <el-form ref="productAttrForm" :model="value" label-width="150px" style="width: 720px" size="small">
      <el-form-item label="规格参数模板：">
        <el-select v-model="value.specParamTemplateId" placeholder="请选择规格参数模板" @change="handleSpecParamTemplateChange">
          <el-option v-for="item in options.specParamTemplateOptions" :key="item.id" :label="item.templateName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(productAttr,idx) in options.specOptions" :key="idx">
            {{ productAttr.name }}：
            <el-checkbox-group v-if="productAttr.handAddStatus===0" v-model="options.specOptions[idx].values">
              <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :key="item" :label="item" class="littleMarginLeft" />
            </el-checkbox-group>
            <div v-else>
              <el-checkbox-group v-model="options.specOptions[idx].values">
                <div v-for="(item,index) in options.specOptions[idx].options" :key="index" style="display: inline-block" class="littleMarginLeft">
                  <el-checkbox :key="item" :label="item" />
                  <el-button type="text" class="littleMarginLeft" @click="handleRemoveProductAttrValue(idx,index)">删除</el-button>
                </div>
              </el-checkbox-group>
              <el-input v-model="addProductAttrValue" style="width: 160px;margin-left: 10px" clearable />
              <el-button class="littleMarginLeft" @click="handleAddProductAttrValue(idx)">增加</el-button>
            </div>
          </div>
        </el-card>
        <el-table style="width: 100%;margin-top: 20px" :data="value.skuStockList" border>
          <el-table-column v-for="(item,index) in options.specOptions" :key="item.id" :label="item.name" align="center">
            <template slot-scope="scope">
              {{ getProductSkuSp(scope.row,index) }}
            </template>
          </el-table-column>
          <el-table-column label="销售价格" width="80" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" />
            </template>
          </el-table-column>
          <el-table-column label="商品库存" width="80" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stock" />
            </template>
          </el-table-column>
          <el-table-column label="库存预警值" width="80" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lowStock" />
            </template>
          </el-table-column>
          <el-table-column label="SKU编号" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuCode" />
            </template>
          </el-table-column>
          <el-table-column label="属性图片：" align="left">
            <template slot-scope="scope">
              <single-upload v-model="scope.row.pic" style="width: 300px;display: inline-block;margin-left: 10px" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="handleRemoveProductSku(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 20px" @click="handleRefreshProductSkuList">刷新列表</el-button>
        <el-button type="primary" style="margin-top: 20px" @click="handleSyncProductSkuPrice">同步价格</el-button>
      </el-form-item>
      <el-form-item v-if="hasAttrPic" label="属性图片：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in selectProductAttrPics" :key="index">
            <span>{{ item.name }}:</span>
            <single-upload v-model="item.pic" style="width: 300px;display: inline-block;margin-left: 10px" />
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="商品参数：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in options.paramOptions" :key="index" :class="{littleMarginTop:index!==0}">
            <div class="paramInputLabel">{{ item.name }}:</div>
            <el-select v-if="item.inputType===1" v-model="options.paramOptions[index].value" class="paramInput">
              <el-option v-for="option in getParamInputList(item.inputList)" :key="option" :label="option" :value="option" />
            </el-select>
            <el-input v-else v-model="options.paramOptions[index].value" class="paramInput" />
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="商品相册：">
        <multi-upload v-model="selectProductPics" />
      </el-form-item>
      <el-form-item label="规格参数：">
        <el-tabs v-model="activeHtmlName" type="card">
          <el-tab-pane label="电脑端详情" name="pc">
            <tinymce v-model="value.detailHtml" :width="572" :height="300" />
          </el-tab-pane>
          <el-tab-pane label="移动端详情" name="mobile">
            <tinymce v-model="value.detailMobileHtml" :width="572" :height="300" />
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="medium" @click="handlePrev">上一步，填写商品促销</el-button>
        <el-button type="primary" size="medium" @click="handleNext">下一步，选择商品关联</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import SpecParamTemplateApi from '@/api/goods/SpecParamTemplateApi'
import SpecApi from '@/api/goods/SpecApi'
import ParamApi from '@/api/goods/ParamApi'
import SingleUpload from '@/components/Upload/SingleUpload'
import MultiUpload from '@/components/Upload/MultiUpload'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'SpuAttr',
  components: { SingleUpload, MultiUpload, Tinymce },
  props: {
    value: {
      type: Object,
      default: function() {
        return {}
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: {
        specParamTemplateOptions: [],
        specOptions: [],
        paramOptions: []
      },
      // 编辑模式时是否初始化成功
      hasEditCreated: false,
      // 选中的商品属性图片
      selectProductAttrPics: [],
      // 可手动添加的商品属性
      addProductAttrValue: '',
      // 商品富文本详情激活类型
      activeHtmlName: 'mobile'
    }
  },
  computed: {
    // 是否有商品属性图片
    hasAttrPic() {
      if (this.selectProductAttrPics.length < 1) {
        return false
      }
      return true
    },
    // 商品的编号
    productId() {
      return this.value.id
    },
    // 商品的主图和画册图片
    selectProductPics: {
      get: function() {
        const pics = []
        if (this.value.image === undefined || this.value.image == null || this.value.image === '') {
          return pics
        }
        pics.push(this.value.image)
        if (this.value.albumPics === undefined || this.value.albumPics == null || this.value.albumPics === '') {
          return pics
        }
        const albumPics = this.value.albumPics.split(',')
        for (let i = 0; i < albumPics.length; i++) {
          pics.push(albumPics[i])
        }
        return pics
      },
      set: function(newValue) {
        if (newValue == null || newValue.length === 0) {
          this.value.image = null
          this.value.albumPics = null
        } else {
          this.value.image = newValue[0]
          this.value.albumPics = ''
          if (newValue.length > 1) {
            for (let i = 1; i < newValue.length; i++) {
              this.value.albumPics += newValue[i]
              if (i !== newValue.length - 1) {
                this.value.albumPics += ','
              }
            }
          }
        }
      }
    }
  },
  watch: {
    productId(newValue) {
      if (!this.isEdit) return
      if (this.hasEditCreated) return
      if (newValue === undefined || newValue == null || newValue === 0) return
      this.handleEditCreated()
    }
  },
  created() {
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      SpecParamTemplateApi.list().then(response => {
        this.options.specParamTemplateOptions = response.data
      })
    },
    handleSpecParamTemplateChange(templateId) {
      SpecApi.list({ templateId }).then(response => {
        this.options.specOptions = response.data
      })
      ParamApi.list({ templateId }).then(response => {
        this.options.paramOptions = response.data
      })
    },
    getProductAttrList(type, cid) {
      const param = { pageNum: 1, pageSize: 3, type: type }
      // 商品属性列表
      SpecParamTemplateApi.list(cid, param).then(response => {
        const list = response.data.records
        if (type === 0) {
          this.options.specOptions = []
          for (let i = 0; i < list.length; i++) {
            let options = []
            let values = []
            if (this.isEdit) {
              if (list[i].handAddStatus === 1) {
                // 编辑状态下获取手动添加编辑属性
                options = this.getEditAttrOptions(list[i].id)
              }
              // 编辑状态下获取选中属性
              values = this.getEditAttrValues(i)
            }
            this.options.specOptions.push({
              id: list[i].id,
              name: list[i].name,
              handAddStatus: list[i].handAddStatus,
              inputList: list[i].inputList,
              values: values,
              options: options
            })
          }
          if (this.isEdit) {
            // 编辑模式下刷新商品属性图片
            this.refreshProductAttrPics()
          }
        } else {
          this.options.paramOptions = []
          for (let i = 0; i < list.length; i++) {
            let value = null
            if (this.isEdit) {
              // 编辑模式下获取参数属性
              value = this.getEditParamValue(list[i].id)
            }
            this.options.paramOptions.push({
              id: list[i].id,
              name: list[i].name,
              value: value,
              inputType: list[i].inputType,
              inputList: list[i].inputList
            })
          }
        }
      })
    },
    handleEditCreated() {
      // 根据规格参数模板ID获取规格和参数
      if (this.value.specParamTemplateId != null) {
        this.handleSpecParamTemplateChange(this.value.specParamTemplateId)
      }
      this.hasEditCreated = true
    },
    // 获取设置的可手动添加属性值
    getEditAttrOptions(id) {
      const options = []
      for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
        const attrValue = this.value.productAttributeValueList[i]
        if (attrValue.productAttributeId === id) {
          const strArr = attrValue.value.split(',')
          for (let j = 0; j < strArr.length; j++) {
            options.push(strArr[j])
          }
          break
        }
      }
      return options
    },
    // 获取选中的属性值
    getEditAttrValues(index) {
      const values = []
      if (index === 0) {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          const sku = this.value.skuStockList[i]
          if (sku.sp1 != null && values.indexOf(sku.sp1) === -1) {
            values.push(sku.sp1)
          }
        }
      } else if (index === 1) {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          const sku = this.value.skuStockList[i]
          if (sku.sp2 != null && values.indexOf(sku.sp2) === -1) {
            values.push(sku.sp2)
          }
        }
      } else {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          const sku = this.value.skuStockList[i]
          if (sku.sp3 != null && values.indexOf(sku.sp3) === -1) {
            values.push(sku.sp3)
          }
        }
      }

      return values
    },
    // 获取属性的值
    getEditParamValue(id) {
      for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
        if (id === this.value.productAttributeValueList[i].productAttributeId) {
          return this.value.productAttributeValueList[i].value
        }
      }
    },
    getInputListArr(inputList) {
      return inputList.split(',')
    },
    handleAddProductAttrValue(idx) {
      const options = this.options.specOptions[idx].options
      if (this.addProductAttrValue === null || this.addProductAttrValue === '') {
        this.$message({
          message: '属性值不能为空',
          type: 'warning',
          duration: 1000
        })
        return
      }
      if (options.indexOf(this.addProductAttrValue) !== -1) {
        this.$message({
          message: '属性值不能重复',
          type: 'warning',
          duration: 1000
        })
        return
      }
      this.options.specOptions[idx].options.push(this.addProductAttrValue)
      this.addProductAttrValue = null
    },
    handleRemoveProductAttrValue(idx, index) {
      this.options.specOptions[idx].options.splice(index, 1)
    },
    getProductSkuSp(row, index) {
      if (index === 0) {
        return row.sp1
      } else if (index === 1) {
        return row.sp2
      } else {
        return row.sp3
      }
    },
    handleRefreshProductSkuList() {
      this.$confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.refreshProductSkuList()
      })
    },
    handleSyncProductSkuPrice() {
      this.$confirm('将同步第一个sku的价格到所有sku,是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.value.skuStockList !== null && this.value.skuStockList.length > 0) {
          const price = this.value.skuStockList[0].price
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            this.value.skuStockList[i].price = price
          }
        }
      })
    },
    refreshProductSkuList() {
      this.value.skuStockList = []
      const skuList = this.value.skuStockList
      // 只有一个属性时
      if (this.options.specOptions.length === 1) {
        const values = this.options.specOptions[0].values
        for (let i = 0; i < values.length; i++) {
          skuList.push({
            sp1: values[i]
          })
        }
      } else if (this.options.specOptions.length === 2) {
        const values0 = this.options.specOptions[0].values
        const values1 = this.options.specOptions[1].values
        for (let i = 0; i < values0.length; i++) {
          if (values1.length === 0) {
            skuList.push({
              sp1: values0[i]
            })
            continue
          }
          for (let j = 0; j < values1.length; j++) {
            skuList.push({
              sp1: values0[i],
              sp2: values1[j]
            })
          }
        }
      } else {
        const values0 = this.options.specOptions[0].values
        const values1 = this.options.specOptions[1].values
        const values2 = this.options.specOptions[2].values
        for (let i = 0; i < values0.length; i++) {
          if (values1.length === 0) {
            skuList.push({
              sp1: values0[i]
            })
            continue
          }
          for (let j = 0; j < values1.length; j++) {
            if (values2.length === 0) {
              skuList.push({
                sp1: values0[i],
                sp2: values1[j]
              })
              continue
            }
            for (let k = 0; k < values2.length; k++) {
              skuList.push({
                sp1: values0[i],
                sp2: values1[j],
                sp3: values2[k]
              })
            }
          }
        }
      }
    },
    refreshProductAttrPics() {
      this.selectProductAttrPics = []
      if (this.options.specOptions.length >= 1) {
        const values = this.options.specOptions[0].values
        for (let i = 0; i < values.length; i++) {
          let pic = null
          if (this.isEdit) {
            // 编辑状态下获取图片
            pic = this.getProductSkuPic(values[i])
          }
          this.selectProductAttrPics.push({ name: values[i], pic: pic })
        }
      }
    },
    // 获取商品相关属性的图片
    getProductSkuPic(name) {
      for (let i = 0; i < this.value.skuStockList.length; i++) {
        if (name === this.value.skuStockList[i].sp1) {
          return this.value.skuStockList[i].pic
        }
      }
      return null
    },
    // 合并商品属性
    mergeProductAttrValue() {
      this.value.productAttributeValueList = []
      for (let i = 0; i < this.options.specOptions.length; i++) {
        const attr = this.options.specOptions[i]
        if (attr.handAddStatus === 1 && attr.options != null && attr.options.length > 0) {
          this.value.productAttributeValueList.push({
            productAttributeId: attr.id,
            name: attr.name,
            type: 1,
            value: this.getOptionStr(attr.options)
          })
        }
      }
      for (let i = 0; i < this.options.paramOptions.length; i++) {
        const param = this.options.paramOptions[i]
        this.value.productAttributeValueList.push({
          productAttributeId: param.id,
          name: param.name,
          type: 2,
          value: param.value
        })
      }
    },
    // 合并商品属性图片
    mergeProductAttrPics() {
      for (let i = 0; i < this.selectProductAttrPics.length; i++) {
        for (let j = 0; j < this.value.skuStockList.length; j++) {
          if (this.value.skuStockList[j].sp1 === this.selectProductAttrPics[i].name) {
            this.value.skuStockList[j].pic = this.selectProductAttrPics[i].pic
          }
        }
      }
    },
    getOptionStr(arr) {
      let str = ''
      for (let i = 0; i < arr.length; i++) {
        str += arr[i]
        if (i !== arr.length - 1) {
          str += ','
        }
      }
      return str
    },
    handleRemoveProductSku(index, row) {
      const list = this.value.skuStockList
      if (list.length === 1) {
        list.pop()
      } else {
        list.splice(index, 1)
      }
    },
    getParamInputList(inputList) {
      return inputList.split(',')
    },
    handlePrev() {
      this.$emit('prevStep')
    },
    handleNext() {
      this.mergeProductAttrValue()
      this.mergeProductAttrPics()
      this.$emit('nextStep')
    },
    handleFinishCommit() {
      this.$emit('finishCommit', this.isEdit)
    }
  }
}
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px
}

.cardBg {
  background: #F8F9FC;
}
</style>
